
import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Drawer, Message } from '@alifd/next';
import { t } from '@lingui/macro';
import { uniqueId } from 'lodash';
import { observer } from 'mobx-react-lite';
import React, { useState, useEffect } from 'react';
import { column, toSelectDataSource, ENUMS } from './stores/definitions';
import { toJS } from 'mobx';
import BaseDrawer from './components/BaseDrawer';
import MoreFuncDropDown from '@/components/MoreFuncDropDown';

const tableId = uniqueId('tauTable-');

const _TITLE_TEXT_TRANSFER = {
  add: t`添加积分转移`,
  view: t`查看积分转移`,
  edit: t`编辑积分转移`,
};

const Integral = () => {
  const [modal, setModal] = useState({
    show: null,
    record: null,
  });
  const [initiator, setInitiator] = useState(null);
  const { transferStore: store, ruleStore } = useStore();

  useEffect(() => {
    store.search = {
      groupIds: [ruleStore._group_id],
    };
    (async () => {
      await init();
    })();
  }, [ruleStore._group_id]);

  async function init() {
    try {
      const res = await store.getUser({
        search: { groupIds: [ruleStore._group_id] },
        pg: { size: 999, page: 0, sort: ['crDate;desc'] },
      });
      setInitiator(res);
    } catch (error) {
      console.log('🚀 _ file: index.jsx:49 _ error:', error);
      throw error;
    }
  }

  // 获取列表数据
  const handleOnSearch = (params) => {
    const { getOnDate, ...searchArgs } = params.values;
    const [from, to] = getOnDate || [];
    store.search = {
      from,
      to,
      groupIds: [ruleStore._group_id],
      ...searchArgs,
    };
  };

  const handleAddTransfer = () => {
    setModal({ show: 'add', record: null });
  };

  const handleOnEdit = (result) => {
    setModal({ show: 'edit', record: result });
  };

  // Modal窗口关闭回调
  const handleCancel = () => {
    setModal({ show: null, record: null });
  };

  const handleOnSubmit = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        const { points, type } = toJS(result);
        const numberPoints = Number(points);
        const { issueName, issueId, issuePhone } = toJS(store.authInfo);
        const { nickname: memberName, value: memberId, phone: memberPhone, memberPoints } = toJS(store.getTransferInfos(toJS(result)?.memberId));
        if (type == 0) {
          if (memberPoints < numberPoints) {
            Message.error({ content: t`积分不足！` });
            return;
          } else if (numberPoints <= 0) {
            Message.error({ content: t`积分必须大于0！` });
            return;
          }
        }
        await store.create({ ...toJS(result), issueName, issueId, issuePhone, memberName, memberId, memberPhone });
        Message.success({ content: t`添加成功` });
        await init();
      } catch (e) {
        Message.error({ content: t`添加失败`, duration: 7000 });
        throw e;
      }
    }
    handleCancel();
  };

  const handleOnUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        const { id, remarks } = toJS(result);
        await store.update({ pointsTradeId: id, remarks });
        Message.success({ content: t`添加成功` });
      } catch (e) {
        Message.error({ content: t`添加失败`, duration: 7000 });
        throw e;
      }
    }
    handleCancel();
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        onSearch={handleOnSearch}
        actions={[
          {
            name: 'btn-transfer',
            title: t`添加积分转移`,
            type: 'primary',
            onClick: handleAddTransfer,
          },
        ]}
        searchItems={[
          {
            name: 'getOnDate',
            type: 'date-range',
            props: {
              placeholder: [t`开始创建时间`, t`结束创建时间`],
            },
          },
          {
            name: 'transactionType',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.type),
              placeholder: t`迁移类型`,
              style: { width: 100 },
            },
          },
          {
            name: 'issue',
            type: 'select',
            props: {
              dataSource: initiator,
              placeholder: t`发起人`,
              style: { width: 200 },
              showSearch: true,
            },
          },
        ]}
        keywordSearch={{
          // enabled: true,
          placeholder: t`请输入关键字搜索`,
        }}
        className="action-panel"
      />
      <div className="content">
        <TauTable
          instanceId={tableId}
          primaryKey="id"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          onFetch={(pg) => {
            store.pg = pg;
          }}
          loading={store.loading}
          dataSource={toJS(store.data)}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('issueName', { width: 100 }),
            column('type', { width: 100 }),
            column('memberGroup', { width: 100 }),
            column('points', { width: 100 }),
            column('crDate', { width: 130, sortable: true }),
            column('remarks', { width: 130 }),
            {
              title: t`操作`,
              dataIndex: 'channelNumber',
              width: 100,
              cell: (_, __, r) => {
                const menu = [
                  {
                    title: t`编辑`,
                    onClick: () => handleOnEdit(r),
                  },
                ];
                return <MoreFuncDropDown dropdownItems={menu} />;
              },
            },
          ]}
        />
      </div>
      <Drawer
        visible={modal.show === 'add' || modal.show === 'view' || modal.show === 'edit'}
        title={_TITLE_TEXT_TRANSFER[modal.show]}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal({ ...modal, toClose: `toClose$${Date.now()}` })}
        width="600px"
      >
        <BaseDrawer
          modal={modal}
          onCancel={handleCancel}
          onSubmit={modal.show == 'add' ? handleOnSubmit : handleOnUpdate}
        />
      </Drawer>
    </TauPage>
  );
};

export default observer(Integral);
